<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <el-dialog v-model="dialogVisible" title="新增文件" width="500" :before-close="closeDialog">
    <el-form :model="dialogFormData" :rules="formRules">
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="dialogFormData.fileType" placeholder="请选择" clearable @change="handleTypeChange">
          <el-option v-for="dict in fileTypes" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="dialogFormData.fileType" label="文件格式" prop="fileFormat">
        <el-select v-model="dialogFormData.fileFormat" placeholder="请选择" clearable>
          <el-option v-for="dict in inputModelTypes" :key="dict.value" :label="dict" :value="dict" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人">
        <span>{{ dialogFormData.createBy }}</span>
      </el-form-item>
      <el-form-item label="创建时间">
        <span>{{ dialogFormData.createTime }}</span>
      </el-form-item>
      <el-form-item v-if="dialogFormData.fileFormat" label="上传文件" prop="file">
        <el-upload ref="uploadRef" v-model:file-list="fileList" action="#" :auto-upload="false" :limit="1" :on-exceed="handleExceed">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer text-center">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="sureDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="AddFileDialog" lang="ts">
import useUserStore from '@/store/modules/user';
import { types } from '@/api/caxDataConversionMajorComponent/index';
import { parseTime } from '@/utils/ruoyi';
import { genFileId } from 'element-plus';
import type { UploadProps, UploadRawFile } from 'element-plus';
import { sourceFileUpload } from '@/api/caxDataConversionMajorComponent/fileManagement/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['call-back']);
const dialogVisible = ref(false);
const userStore = useUserStore();
const dialogFormData = reactive({
  fileType: '',
  fileFormat: '',
  createBy: userStore.nickname,
  createTime: parseTime(new Date())
});
const uploadRef = ref<ElUploadInstance>();
const fileList = ref([]);
const fileTypes = ref(types);
const inputModelTypes = ref([]);
let intervalId = null;
const formRules = ref<ElFormRules>({
  fileType: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
  fileFormat: [{ required: true, message: '文件格式不能为空', trigger: 'change' }],
  file: [{ required: true, message: '文件不能为空', trigger: 'change' }]
});
const updateTime = () => {
  dialogFormData.createTime = parseTime(new Date());
};
const openDialog = () => {
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
};
const handleTypeChange = () => {
  if (dialogFormData.fileType) {
    const obj = fileTypes.value.find((item) => item.value === dialogFormData.fileType);
    if (obj) {
      inputModelTypes.value = obj.inputType;
      return;
    }
  }
  let arr = [];
  fileTypes.value.forEach((element) => {
    arr = [...arr, ...element.inputType];
  });
  inputModelTypes.value = arr;
};
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
};
const checkFile = () => {
  const name = fileList.value[0].name;
  const type = name.substring(name.lastIndexOf('.')).toLocaleLowerCase();
  const fileFormat = '.' + dialogFormData.fileFormat.toLocaleLowerCase();
  if (type !== fileFormat) {
    proxy?.$modal.msgError(`限制上传${dialogFormData.fileFormat}类型文件`);
    return false;
  }
  return true;
};
const sureDialog = async () => {
  if (!fileList.value.length) {
    proxy?.$modal.msgError(`请上传文件`);
    return false;
  }
  if (!checkFile()) {
    return false;
  }
  if (!fileList.value.length) {
    proxy?.$modal.msgError(`请上传文件`);
    return false;
  }
  const file = fileList.value[0];
  const formData = new FormData();
  formData.append('type', dialogFormData.fileType);
  formData.append('files', file.raw);
  await sourceFileUpload(formData);
  closeDialog();
  proxy?.$modal.msgSuccess(`新增文件成功！`);
  emit('call-back');
};
onMounted(() => {
  handleTypeChange();
  // 每秒更新一次时间
  intervalId = setInterval(updateTime, 1000);
});

onUnmounted(() => {
  // 清除定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
});
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped></style>
